/*
 * Copyright (C) 2014 VenomVendor <info@VenomVendor.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.naizhuai.ui.adapter.business;

import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.naizhuai.R;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.ImageBean;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.ui.mianbusiness.action.presenter.DownloadImageApiStoreIml;
import com.naizhuai.ui.mianbusiness.action.presenter.UploadImageApiStoreIml;
import com.naizhuai.util.DeviceUtils;
import com.naizhuai.util.FileNameUtils;
import com.naizhuai.util.NaizhuAILog;
import com.yalantis.ucrop.UCropActivity;
import com.yalantis.ucrop.callback.BitmapCropCallback;
import com.yalantis.ucrop.view.CropImageView;
import com.yalantis.ucrop.view.GestureCropImageView;
import com.yalantis.ucrop.view.TransformImageView;
import com.yalantis.ucrop.view.UCropView;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func1;

import static android.content.ContentValues.TAG;

public class ActionContractEditAdapterHolder extends RecyclerView.Adapter {

    private BaseActivity mContext;
    private List<CompareImageBean> imageEditList;

    public static final String PRE_GES_VIEW_KEY = "pre_ges_view_key";
    public static final String AFT_GES_VIEW_KEY = "aft_ges_view_key";

    private SparseArray<Map<String, GestureCropImageView>> gesImageMapList;
    private PagerManageImageListener listener;

    public static final int ITEM_IMAGE_CONTRACT = 0;
    public static final int ITEM_ADD_IMAGE = 1;

    private boolean canEditModel = true;


    public static final int NONE = 0;
    public static final int SCALE = 1;
    public static final int ROTATE = 2;
    public static final int ALL = 3;
    private int[] mAllowedGestures = new int[]{SCALE, ROTATE, ALL};

    private int resetPosition = -1;

    private Bitmap.CompressFormat mCompressFormat = DEFAULT_COMPRESS_FORMAT;

    public static final int DEFAULT_COMPRESS_QUALITY = 90;

    public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;

    public ActionContractEditAdapterHolder(BaseActivity context, List<CompareImageBean> imageEditList, PagerManageImageListener listener) {
        this.mContext = context;
        this.imageEditList = imageEditList;
        gesImageMapList = new SparseArray<>();
        this.listener = listener;
    }


    /**
     * 设置不同的类型：
     * 0：表示展示的title的item
     * 1：展示的item内容
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        return ITEM_IMAGE_CONTRACT;
    }


    @Override
    public int getItemCount() {
        return imageEditList.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View sView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_action_edit_contract_image, parent, false);
        return new ActionEditItemHolder(sView, mContext);
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ActionEditItemHolder) {
            ActionEditItemHolder imageHolder = (ActionEditItemHolder) holder;

            ImageBean imageBefore = imageEditList.get(position).getBeforeImage();
            ImageBean imageAfter = imageEditList.get(position).getAfterImage();
            GestureCropImageView aftGestureImageView;
            try {
                if (imageBefore != null && imageBefore.getImageUriInput() != null) {
                    imageHolder.preEditImage.setUserScrollEvent(true);
                    if (gesImageMapList.get(position) != null)
                        gesImageMapList.get(position).put(PRE_GES_VIEW_KEY, imageHolder.preGestureImageView);
                    else {
                        Map<String, GestureCropImageView> gesImageMap = new HashMap<>();
                        gesImageMap.put(PRE_GES_VIEW_KEY, imageHolder.preGestureImageView);
                        gesImageMapList.put(position, gesImageMap);
                    }
                    imageHolder.preGestureImageView.setImageUri(imageBefore.getImageUriInput(), imageBefore.getImageUriOutput());
                } else {
                    imageHolder.preEditImage.setUserScrollEvent(false);
                }
                if (imageAfter != null && imageAfter.getImageUriInput() != null) {
                    imageHolder.aftEditImage.setUserScrollEvent(true);
                    if (resetPosition == position) {
                        imageHolder.aftEditImage.resetCropImageView();
                        resetPosition = -1;
                    }
                    aftGestureImageView = imageHolder.aftEditImage.getCropImageView();
                    if (gesImageMapList.get(position) == null) {
                        Map<String, GestureCropImageView> gesImageMap = new HashMap<>();
                        gesImageMap.put(AFT_GES_VIEW_KEY, aftGestureImageView);
                        gesImageMapList.put(position, gesImageMap);
                    } else {
                        gesImageMapList.get(position).put(AFT_GES_VIEW_KEY, aftGestureImageView);
                    }
                    initGestureCropImageView(aftGestureImageView, imageHolder.aftEditImage);
                    aftGestureImageView.setImageUri(imageAfter.getImageUriInput(), imageAfter.getImageUriOutput());
                    imageHolder.imageLayout.setVisibility(View.GONE);
                    imageHolder.changeUploadView.setVisibility(View.VISIBLE);
                } else {
                    imageHolder.aftEditImage.setUserScrollEvent(false);
                    imageHolder.imageLayout.setVisibility(View.VISIBLE);
                    imageHolder.changeUploadView.setVisibility(View.GONE);
                }
            } catch (Exception ignored) {
            }
        }
    }

    private void initGestureCropImageView(GestureCropImageView gestView, UCropView view) {
        gestView.setCanTouchAndMove(canEditModel);
        gestView.setTransformImageListener(new TransImageListener(view));
        setAllowedGestures(gestView, 0);
    }

    private void setAllowedGestures(GestureCropImageView gesImage, int tab) {
        gesImage.setScaleEnabled(mAllowedGestures[tab] == ALL || mAllowedGestures[tab] == SCALE);
        gesImage.setRotateEnabled(mAllowedGestures[tab] == ALL || mAllowedGestures[tab] == ROTATE);
    }


    public void stopCropVIew() {
        for (int index = 0; index < gesImageMapList.size(); index++) {
            Map<String, GestureCropImageView> gesImageMap = gesImageMapList.get(index);
            for (GestureCropImageView image : gesImageMap.values()) {
                if (image != null)
                    image.cancelAllAnimations();
            }
        }
    }

    public boolean isCanEditModel() {
        return canEditModel;
    }

    public void setCanEditModel(boolean canEditModel) {
        this.canEditModel = canEditModel;
    }

    class UploadImageClickListener implements View.OnClickListener {

        private ActionEditItemHolder holder;

        public UploadImageClickListener(ActionEditItemHolder holder) {
            this.holder = holder;
        }

        @Override
        public void onClick(View v) {
            Album.image(mContext) // 选择图片。
                    .singleChoice()
                    .requestCode(200)
                    .camera(true)
                    .columnCount(3)
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                            ImageBean bean=new ImageBean();
                            bean.setImageUriInput(FileNameUtils.filePath2Uri(result.get(0).getPath()));
                            bean.setImageUriOutput(FileNameUtils.getCacheUri(result.get(0).getName(), mContext));
                            resetPosition = holder.getAdapterPosition();
                            listener.uploadImage(bean, holder.getAdapterPosition());
                        }
                    }).start();
        }
    }

    private volatile int cropCount = 0;

    public void cropAndSaveImages() {
        cropCount = 0;
        for (int index = 0; index < gesImageMapList.size(); index++) {
            if(!cropAndSaveSingleImage(gesImageMapList.get(index).get(PRE_GES_VIEW_KEY), index, PRE_GES_VIEW_KEY)){
                listener.emptyImageError();
                return;
            }
            if(!cropAndSaveSingleImage(gesImageMapList.get(index).get(AFT_GES_VIEW_KEY), index, AFT_GES_VIEW_KEY)){
                listener.emptyImageError();
                return;
            }
        }
    }

    private boolean cropAndSaveSingleImage(GestureCropImageView gestView, int position, String imagePosition) {
        if(gestView==null)
            return false;
        gestView.cropAndSaveImage(mCompressFormat, DEFAULT_COMPRESS_QUALITY, new BitmapCropCallback() {

            @Override
            public void onBitmapCropped(@NonNull Uri resultUri, int offsetX, int offsetY, int imageWidth, int imageHeight) {
                listener.cropImage(resultUri, position, imagePosition);
                cropCount++;
                if (cropCount == gesImageMapList.size() * 2)
                    listener.cropImagesFinished();
            }

            @Override
            public void onCropFailure(@NonNull Throwable t) {
                listener.cropImageErrer(t, position);
            }
        });
        return true;
    }


    public interface PagerManageImageListener {
        void uploadImage(ImageBean s, int position);

        void emptyImageError();

        void downloadImageError(Throwable e);

        void onLoadTransComplete();

        void onLoadTransFailure(@NonNull Exception e);

        void onTransRotate(float currentAngle);

        void onTransScale(float currentScale);

        void cropImage(Uri cropUri, int position, String cropPosition);

        void cropImagesFinished();

        void cropImageErrer(Throwable t, int position);
    }

    class TransImageListener implements TransformImageView.TransformImageListener {
        private UCropView editImage;

        public TransImageListener(UCropView editImage) {
            this.editImage = editImage;
        }

        @Override
        public void onLoadComplete() {
            editImage.animate().alpha(1).setDuration(300).setInterpolator(new AccelerateInterpolator());
            listener.onLoadTransComplete();
        }

        @Override
        public void onLoadFailure(@NonNull Exception e) {
            listener.onLoadTransFailure(e);
        }

        @Override
        public void onRotate(float currentAngle) {
            listener.onTransRotate(currentAngle);
        }

        @Override
        public void onScale(float currentScale) {
            listener.onTransScale(currentScale);
        }
    }


    public class ActionEditItemHolder extends RecyclerView.ViewHolder {

        UCropView preEditImage;
        GestureCropImageView preGestureImageView;

        UCropView aftEditImage;

        RelativeLayout imageLayout;
        TextView uploadView;
        TextView changeUploadView;

        ImageView textImage;

        public ActionEditItemHolder(View view, BaseActivity mContext) {
            super(view);
            preEditImage = view.findViewById(R.id.pre_crop_image);
            preGestureImageView = preEditImage.getCropImageView();

            aftEditImage = view.findViewById(R.id.after_crop_image);


            imageLayout = view.findViewById(R.id.add_image_layout);
            uploadView = view.findViewById(R.id.upload_image);
            changeUploadView = view.findViewById(R.id.change_upload_image);
            textImage = view.findViewById(R.id.text_image);

            initGestureCropImageView(preGestureImageView, preEditImage);

            uploadView.setOnClickListener(new UploadImageClickListener(this));
            changeUploadView.setOnClickListener(new UploadImageClickListener(this));
            view.getLayoutParams().height=DeviceUtils.getScreenDevice(mContext)[0];
        }


    }

}
